import { defineStore } from "pinia"
import { onMounted, reactive, ref } from "vue"
import { get, post } from "@/utils/api"
import { MessagePlugin } from "tdesign-vue-next"

export const useUserAuthorizationStore = defineStore("userAuthorization", () => {
  onMounted(async () => {
    await table.getData()
  })
  // 通用模块
  const common = {
    formData: reactive({
      user_id: "",
      app_name: "",
      app_id: "",
      type: 0,
      body: "",
      status: 1,
      over_date: ""
    }),
    clear: () => {
      Object.assign(common.formData, {
        user_id: "",
        type: 0,
        body: "",
        status: 1,
        over_date: ""
      })
    },
    typeOptions: [
      {
        label: "域名",
        value: 0
      },
      {
        label: "IP",
        value: 1
      }
    ],
    validator: {
      bodyValidator: (val: string) => {
        // 域名
        const domainPattern = /^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\.)+[A-Za-z]{2,6}$/
        // IP
        const ipPattern = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/
        if (common.formData.type === 0 && !domainPattern.test(val)) {
          return { result: false, message: "请输正确的域名", type: "error" }
        }
        if (common.formData.type === 1 && !ipPattern.test(val)) {
          return { result: false, message: "请输正确的IP", type: "error" }
        }
        return { result: true }

      }
    },
    rules: { body: [{ required: true, trigger: "change" }, { validator: (val: any) => common.validator.bodyValidator(val) }] }
  }

  // 编辑模块
  const editDialog = {
    loading: ref(false),
    visible: ref(false),
    editId: ref(),
    formDataAssign: (row: any) => {
      editDialog.visible.value = true
      editDialog.editId.value = row.id
      row.user_id = row.user_id.toString()
      Object.assign(common.formData, row)
    },
    edit: async ({ validateResult, firstError, e }: any) => {
      e.preventDefault()
      if (validateResult === true) {
        await editDialog.confirmEdit()
      } else {
        console.log("Validate Errors: ", firstError, validateResult)
      }
    },
    confirmEdit: async () => {
      editDialog.loading.value = true
      try {
        const response = await post("/api/authorization/update", {
          id: editDialog.editId.value,
          data: common.formData
        })
        MessagePlugin(response.status, response.message)
        if (response.status === "success") {
          editDialog.visible.value = false
          await table.getData()
          table.key.value++ // 重新渲染表格
        }
      } catch (err) {
        console.log(err)
      } finally {
        editDialog.loading.value = false
      }
    }
  }
  // 表格模块
  const table = {
    data: ref([]),
    getData: async () => {
      table.loading.value = true
      try {
        table.data.value = await get("/api/authorization/getAll")
      } catch (err) {
        console.log(err)
      } finally {
        table.loading.value = false
      }
    },
    loading: ref(false),
    key: ref(0),
    searchData: ref(""),
    search: async () => {
      table.loading.value = true
      table.data.value = await post("/api/authorization/search", { body: table.searchData.value })
      table.loading.value = false
    },
    refresh: async () => {
      await table.getData()
      table.key.value++
      table.searchData.value = ""
    }
  }

  return {
    table,
    common,
    editDialog
  }
})
